const { VUE_APP_BASE_URL } = process.env;
import { rsaEncrypt } from '@/utils/security.js';
import utils from '@/utils/utils.js';

let aesKey = ''; // 声明全局 aes 密钥
/**
 * 上传文件:仅支持单文件上传
 */
function postFile(filePath, type) {
  aesKey = utils.getAesKey(32); //每次匹配拦截 生成不同的 aes 密钥
  const isPath = typeof filePath === 'string';
  const token = uni.getStorageSync('tokenSer' + process.env.VUE_APP_PLATFORMID);
  const DeviceType = uni.getSystemInfoSync().deviceType;
  const DeviceId = uni.getSystemInfoSync().deviceId;
  return new Promise((reslove, reject) => {
    uni.uploadFile({
      url:
        `${VUE_APP_BASE_URL}/energy-servicer-mapi/ser-mapi/file/v1/upload?type=` +
        type,
      methods: 'POST',
      file: isPath ? undefined : filePath,
      filePath: isPath ? filePath : undefined,
      name: 'file',
      header: {
        Authorization: token ? token : aesKey,
        DeviceType: DeviceType,
        DeviceId: DeviceId,
        PlatformId: process.env.VUE_APP_PLATFORMID,
        RandomStr: rsaEncrypt(aesKey),
        Sign: aesKey,
        UserType: 'ser',
        TimeStamp: new Date().getTime().toString(),
        TerminalType:
          uni.getSystemInfoSync().uniPlatform == 'web' ? 'h5' : 'android',
      },
      success: ({ data }) => {
        reslove(JSON.parse(data));
      },
      fail: reject,
    });
  });
}

export { postFile };
